package com.example.demo.interceptor;


import com.example.demo.config.AppConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {

   @Value("${czq-forum.login.url}")
    private String defaultURL;



    //对请求的预处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从session中获取用户信息
        HttpSession session = request.getSession();
        //2.判断session是否有效
        if(session!=null && session.getAttribute(AppConfig.USER_SESSION_KEY)!=null){
            return true;
        }
        //3.校验URL是否正确
        if(!defaultURL.startsWith("/")){
            defaultURL = "/" + defaultURL;
        }
        //4.如果用户未登录，跳转到登录页面
        response.sendRedirect(defaultURL);
        //返回false，请求将被拦截，转到登录页面
        return false;
    }
}
